/* eslint-disable prettier/prettier */

//cli: nest g gateway chat
import {
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayInit,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
 } from '@nestjs/websockets';
 import { Logger } from '@nestjs/common';
 import { Socket, Server } from 'socket.io';
 
 @WebSocketGateway({
   namespace: 'game',
   cors: {
     origin: '*',
   },
 })
 export class GameGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
 
  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('GameGateway');
  users = new Map<string, any>();
  gameState: any = null;

  @SubscribeMessage('registerUser')
  registerUser(client: Socket, payload: any): void {
  //  this.server.emit('msgToClient', payload);   //给所有人(包括自己)广播
    // this.users.push(payload.id);
    this.users.set(client.id, payload);
    // client.broadcast.emit('update', payload);   //给除了自己的其他人广播
    const users = {};
    this.users.forEach((value,key)=>{
      users[key] = value
    })
    this.server.emit('userIn',{
      users,
      // users: this.users,
      gameState: this.gameState,
    });   //给除了自己的其他人广播
  }


  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, payload: any): void {
  //  this.server.emit('msgToClient', payload);   //给所有人(包括自己)广播
    // this.users.push(payload.id);
    client.broadcast.emit('update', payload);   //给除了自己的其他人广播
  }
 
  @SubscribeMessage('updateGameState')
  updateGameState(client: Socket, payload: any): void {
  //  this.server.emit('msgToClient', payload);   //给所有人(包括自己)广播
    // this.users.push(payload.id);
    // client.broadcast.emit('update', payload);   //给除了自己的其他人广播
    this.gameState = payload.gameState;
    client.broadcast.emit('gameStateUpdated', payload);   //给除了自己的其他人广播
  }

  afterInit(server: Server) {
   this.logger.log('Init');
  }
 
  handleDisconnect(client: Socket) {
   this.logger.log(`Client disconnected: ${client}`);
   // Notify connected clients of current users
   this.users.delete(client.id)
   this.server.emit('userOut', client.id);
  }
 
  handleConnection(client: Socket, ...args: any[]) {
  //  this.users.push(client.id);
   this.logger.log(`Client connected: ${client.id}`);
   // Notify connected clients of current users
  //  this.server.emit('userIn', this.users);
  //  return client.id
  // this.server.emit('userIn',{
  //   users: this.users,
  //   gameState: this.gameState,
  // });   //给除了自己的其他人广播
  }
 }